import os
from fastapi import APIRouter, HTTPException
from starlette.responses import JSONResponse

router = APIRouter(prefix="/api", tags=["图片管理"])

@router.get("/images")
async def get_images(area: str = "山东省"):
    folder_path = f'lucky_web/public/photo/{area}'
    current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    full_folder_path = os.path.join(current_dir, folder_path)

    try:
        images = []
        for file in os.listdir(full_folder_path):
            if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
                images.append(f"{area}/{file}")
        return JSONResponse(status_code=200, content=images)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/image_paths")
async def get_image_paths(area: str = "山东省"):
    folder_path = f'lucky_web/public/photo/{area}'
    current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    full_folder_path = os.path.join(current_dir, folder_path)

    try:
        images = []
        for file in os.listdir(full_folder_path):
            if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
                absolute_path = os.path.abspath(os.path.join(full_folder_path, file))
                images.append(absolute_path)
        return JSONResponse(status_code=200, content=images)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/visited_areas")
async def get_visited_areas():
    folder_path = 'lucky_web/public/photo'
    current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    full_folder_path = os.path.join(current_dir, folder_path)

    try:
        areas = [name for name in os.listdir(full_folder_path)
                if os.path.isdir(os.path.join(full_folder_path, name))]
        return JSONResponse(status_code=200, content=areas)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e)) 